package com.yzh;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 商品的操作类
 *
 */
public class ProductDaoImpl implements ProductDao {
    //存储商品的集合
    private static List<Product> productList = new ArrayList<Product>();

    //静态代码块  只执行一次  对静态变量进行初始化操作
    static {
        productList.add(new Product(1,"    华为手机    ",10000,"red    ",15,200));
        productList.add(new Product(2,"    笔记本    ",10.5,"black",10,100));
        productList.add(new Product(3,"    卫生纸    ",3.1,"    green ",5,1000));
    }

    //添加商品
    public void add (Product product){
        //大量循环
        //判断id是否存在
        for (int i = 0; i < productList.size(); i++) {
            Product p1 = productList.get(i);
            if (p1.getId() == product.getId()){
                System.out.println("商品编号已经存在，填加失败");
                return;
            }else {
                productList.add(product);
                System.out.println("添加成功");
            }
        }
    }

    //获取商品
    public List<Product> findAll(){
        return productList;
    }
    //根据ID查找商品
    public Product findByID(int id){
        //逐个比较id  先获取id
        for (int i = 0; i < productList.size(); i++) {
            //逐个获取商品
            Product product = productList.get(i);
            if (product.getId()==id){
                //找到了  返回产品
                return product;
            }
        }
        //没有匹配的
        return null ;
    }
}